package com.deng.wxmessagecallback.service;

import cn.hutool.http.HttpUtil;
import me.chanjar.weixin.common.bean.WxAccessToken;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wbdengtt
 * @date 2021/1/12 16:10
 */
@Service
public class TokenService {
    /**
     * 这个是获取Demo(一个自建应用)的access_token
     * @return 返回token
     */
    @Cacheable(value = "qiyeweixin::token::app::demo")
    public String getDemoAccessToken() {
        // 书写到配置是不是更好
        String corpSecret = "dYdp-QDoWVb5LvIeYsF9TNtzeop_UP3VaCgbZeAZ5kI";
        return getAccessToken(corpSecret);
    }

    /**
     * 获取外部联系人客户联需要的token
     * @return 返回客户联系的token
     */
    @Cacheable(value = "qiyeweixin::token::ExternalContact")
    public String getExternalContactToken() {
        // 书写到配置更好
        String corpSecret = "eTpoKupuy8j0Rk7rgpUpWwAdo9hF7lzcRffZbaxwjvM";
        return getAccessToken(corpSecret);
    }

    /**
     * 获取通讯录同步的token
     * 能用中文编码就好了。这个通讯录addressBook估计乍一看看不出是通讯录的意思
     * @return 返回通讯录token
     */
    @Cacheable(value = "qiyeweixin::token::addressBook")
    public String getAddressBookAccessToken () {
        String corpSecret = "WMaZQpw7bnnLGcVHMPuyarOC5nNC0_D_G2zDyyV8Gvc";
        return getAccessToken(corpSecret);
    }



    private String getAccessToken(String secret) {
        // 需要配置从apollo获取
        String corpId = "ww1188f8d8b093846c";
        // 这些固定的参数是不是集中一个类里面去好些
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
        Map<String, Object> map = new HashMap<>();
        map.put("corpid",corpId);
        map.put("corpsecret",secret);
        String tokenString = HttpUtil.get(url,map);
        String accessToken = WxAccessToken.fromJson(tokenString).getAccessToken();
        return accessToken;

    }
}
